import React, { useEffect, useState } from 'react'
import { Button, message, Space, Spin, Table } from 'antd'
import dayjs from 'dayjs'
import http from '@/utils/request'
import Filter from '@/components/filter'
import TeamDrawer from './teamDrawer'
import type { teamType } from '@/types'
import { listToMap, teamTypes } from '@/assets/dict'
import { authority } from '@/assets/dict/authCode'

const RoleList: React.FC = () => {
  const [dataSource, setDataSource] = useState<teamType[]>([])
  const [currentTeam, setCurrentTeam] = useState<teamType>()
  const [isDrawerOpen, setIsDrawerOpen] = useState(false)
  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(false)
  const [pageConfig, setPageConfig] = useState({
    pageSize: 10,
    pageNum: 1,
    current: 1,
    teamName: '',
    teamLeaderName: ''
  })
  const [loadFlag, setLoadFlag] = useState<number>(new Date().getTime())

  const editTeam = (row: teamType) => {
    setCurrentTeam(row)
    setIsDrawerOpen(true)
  }

  const addTeam = () => {
    setCurrentTeam({})
    setIsDrawerOpen(true)
  }

  const initTable = () => {
    setPageConfig((config) => ({
      ...config,
      pageNum: 1
    }))
    setLoadFlag(new Date().getTime())
  }

  const queryTeamList = () => {
    setLoading(true)
    const { pageNum, pageSize, teamLeaderName, teamName } = pageConfig
    http.post('/disp/biz/team/page', {
      pageNum,
      pageSize,
      teamLeaderName,
      teamName
    }).then(res => {
      setTotal(res.data.total || 0)
      setDataSource(res.data.list || [])
    }).finally(() => {
      setLoading(false)
    })
  }

  useEffect(() => {
    queryTeamList()
  }, [loadFlag])

  const pageChange = (pageNum: number, pageSize: number) => {
    pageConfig.pageSize = pageSize
    pageConfig.pageNum = pageNum
    pageConfig.current = pageNum
    queryTeamList()
  }

  const filterOptions = [{
    type: 'input',
    key: 'teamName',
    label: '团队名称'
  }, {
    type: 'input',
    key: 'teamLeaderName',
    label: '领导名称'
  }]

  const filterChange = (val: any, key: string) => {
    setPageConfig((config) => ({
      ...config,
      pageNum: 1,
      current: 1,
      [key]: val
    }))
  }

  interface columnType {
    title: string;
    dataIndex?: string;
    key: string;
    render?: any
  }

  const columns: columnType[] = [
    {
      title: '团队名称',
      dataIndex: 'teamName',
      key: 'teamName'
    },
    {
      title: '管理者',
      dataIndex: 'teamLeaderName',
      key: 'id'
    },
    {
      title: '团队类型',
      dataIndex: 'teamType',
      key: 'id',
      render: (_: any, record: any) => (
        <p>{ listToMap(teamTypes)[record.teamType] || '-'}</p>
      )
    }, {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (_: any, record: any) => (
        <p>{dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss')}</p>
      )
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, row: any) => (
        <Space size="middle">
          {authority('team-list-edit', <Button size="small" type="link" onClick={() => editTeam(row)}>编辑</Button>)}
          {
            row.status === 'Enable' ?
              authority('team-list-switch', <Button onClick={() => handleStatusChange(row, 'disable')} size="small" type="link">停用</Button>) :
              authority('team-list-switch', <Button onClick={() => handleStatusChange(row, 'enable')} size="small" type="link">启用</Button>)
          }
        </Space>
      )
    }
  ]

  const handleStatusChange = (row: teamType, type: string) => {
    setLoading(true)
    http.post(`/disp/biz/team/${type}`, {
      id: row?.id
    }).then(() => {
      message.success('操作成功')
    }).catch(err => {
      message.error(err.msg || '操作失败')
    }).finally(() => {
      initTable()
      setLoading(false)
    })
  }

  const handleClose = (refresh: boolean) => {
    setIsDrawerOpen(false)
    if (refresh) {
      initTable()
    }
  }
  return (
    <Spin spinning={loading}>
      <Filter items={filterOptions} onChange={filterChange} onSure={queryTeamList} />
      <div className="flex-row" style={{ width: '100%' }}>
        <div className="flex1"/>
        {authority('team-list-add', <Button onClick={addTeam}>添加</Button>)}
      </div>
      <Table
        pagination={{ 
          position: ['bottomRight'], 
          ...pageConfig, 
          total, 
          onChange: pageChange, 
          showTotal: (total) => `共 ${total} 条`,
          pageSizeOptions: ['10', '20', '30', '50'],
          showSizeChanger: true
        }}
        dataSource={dataSource}
        columns={columns}
        rowKey="id" />
      <TeamDrawer isOpen={isDrawerOpen} team={currentTeam} onClose={handleClose} />
    </Spin>
  )
}
export default RoleList